package com.zsk.tool.bytes;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.lucene.util.RamUsageEstimator;

/**
 * 获取一个Java对象实际占用内存大小,第三方工具lucene-core
 *
 * @author keke
 * @date 2021/03/03
 */
public class ObjectSize {
    public static class User {
        private String name;
        private int age;
        private String address;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public User() {
            super();
        }

        public User(String name, int age, String address) {
            super();
            this.name = name;
            this.age = age;
            this.address = address;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        int size = 1000000;
        List<ObjectSize.User> list = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            list.add(new User(uuid, i, uuid));
        }
        System.out.println(" 创建100w条数据耗时：" + (System.currentTimeMillis() - start) / 1000.0 + "s");
        // 计算指定对象及其引用树上的所有对象的综合大小，单位字节
        long s1 = RamUsageEstimator.sizeOf(list);

        // 计算指定对象本身在堆空间的大小，单位字节
        long s2 = RamUsageEstimator.shallowSizeOf(list);
        long s3 = RamUsageEstimator.shallowSizeOf(new Integer(0));

        // 计算指定对象及其引用树上的所有对象的综合大小，返回可读的结果，如：2KB
        String s4 = RamUsageEstimator.humanSizeOf(list);

        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
        System.out.println(s4);
    }

}
